package com.logicbus.backend;

import com.alogic.xscript.*;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonObject;
import com.anysoft.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;

import java.util.HashMap;

/**
 * 缺省实现
 *
 * @since 1.6.14.12 [20210617 duanyy]
 */
public class DefaultServicePathTrie extends ServicePathTrie<String> implements Configurable, XMLConfigurable {
    protected static final Logger LOG = LoggerFactory.getLogger(DefaultServicePathTrie.class);
    protected static final String ObjectId = "$path-trie";

    protected Logiclet onLoad = null;

    @Override
    public void configure(Properties p) {
        if (onLoad != null){
            LogicletContext logicletContext = new LogicletContext(Settings.get());
            try {
                logicletContext.setObject(ObjectId, this);
                XsObject doc = new JsonObject("root",new HashMap<String,Object>());
                onLoad.execute(doc,doc, logicletContext, null);
            }catch (Exception ex){
                LOG.info("Failed to execute onload script" + ExceptionUtils.getStackTrace(ex));
            }finally{
                logicletContext.removeObject(ObjectId);
            }
        }
    }

    @Override
    public void configure(Element e, Properties p) {
        XmlElementProperties props = new XmlElementProperties(e,p);
        Element onLoadElem = XmlTools.getFirstElementByPath(e, "on-load");
        if (onLoadElem != null){
            onLoad = Script.create(onLoadElem, props);
        }

        configure(props);
    }

    /**
     * 插入脚本
     */
    public static class Insert extends AbstractLogiclet {
        protected String $id;
        protected String $pattern;
        public Insert(String tag, Logiclet p) {
            super(tag, p);
        }

        @Override
        public void configure(Properties p){
            super.configure(p);
            $id = PropertiesConstants.getRaw(p,"id","");
            $pattern = PropertiesConstants.getRaw(p,"pattern","");
        }

        @Override
        protected void onExecute(XsObject root,XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
            ServicePathTrie<String> trie = ctx.getObject(ObjectId);
            if (trie != null){
                String id = PropertiesConstants.transform(ctx,$id,"");
                String pattern = PropertiesConstants.transform(ctx,$pattern,"");
                if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(pattern)){
                    trie.insert(pattern,id);
                }
            }
        }
    }
}
